package org.m2acsi.boundary;

import java.util.Date;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.m2acsi.entities.Consultation;
import org.m2acsi.entities.Consultation_;
import org.m2acsi.entities.Task;
import org.m2acsi.entities.User;

@Stateless
public class ConsultationEJB extends BaseEJB<Consultation> {

    @PersistenceContext(unitName = "taskManagerPU")
    EntityManager em;

    public ConsultationEJB() {
        super(Consultation.class);
    }

    @Override
    public void remove(Consultation entity) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public EntityManager em() {
        return em;
    }

    public Date lastConsultation(Task task, User user) {
        try {
            CriteriaBuilder cBuilder = em.getCriteriaBuilder();
            CriteriaQuery<Consultation> cQuery = cBuilder.createQuery(entityClass);
            Root<Consultation> c = cQuery.from(entityClass);
            cQuery.select(c);
            cQuery.where(cBuilder.and(
                    cBuilder.equal(c.get(Consultation_.task), task),
                    cBuilder.equal(c.get(Consultation_.user), user)
            ));
            cQuery.orderBy(cBuilder.desc(c.get(Consultation_.creationDate)));

            return em.createQuery(cQuery).getResultList().get(0).getCreationDate();
        } catch (Exception e) {
            return null;
        }
    }

    public Date lastConsultationOnTaskDetails(Task task, User user) {
        try {
            CriteriaBuilder cBuilder = em.getCriteriaBuilder();
            CriteriaQuery<Consultation> cQuery = cBuilder.createQuery(entityClass);
            Root<Consultation> c = cQuery.from(entityClass);
            cQuery.select(c);
            cQuery.where(cBuilder.and(
                    cBuilder.equal(c.get(Consultation_.task), task),
                    cBuilder.equal(c.get(Consultation_.user), user)
            ));
            cQuery.orderBy(cBuilder.desc(c.get(Consultation_.creationDate)));

            return em.createQuery(cQuery).getResultList().get(1).getCreationDate();
        } catch (Exception e) {
            return null;
        }
    }

}
